﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace nMongo.Tests
{
    [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
    sealed class DontGenerateMockAttribute : Attribute
    {
    }

    public class MockGenerator
    {
        #region Random
        private static readonly Random random = new Random();
        private static readonly object trava = new object();
        private static int RandomNumber(int min, int max)
        {
            lock (trava)
            {
                return random.Next(min, max);
            }
        }
        private static void RandomBytes(byte[] buffer)
        {
            lock (buffer)
            {
                random.NextBytes(buffer);
            }
        }
        #endregion

        public static T GenerateOne<T>() where T : class, new()
        {
            T objeto = new T();
            foreach (PropertyInfo propriedade in typeof(T).GetProperties())
            {
                if (propriedade.CustomAttributes.Count(x => x.AttributeType == typeof(DontGenerateMockAttribute)) == 1)
                    continue;

                object valor;
                if (propriedade.PropertyType == typeof(string))
                {
                    valor = Guid.NewGuid().ToString() + Path.GetRandomFileName();
                }
                else if (propriedade.PropertyType == typeof(DateTime))
                {
                    valor = DateTime.Now.AddDays(RandomNumber(15, 200));
                }
                else if (propriedade.PropertyType == typeof(bool))
                {
                    valor = Convert.ToBoolean(RandomNumber(0, 2));
                }
                else if (propriedade.PropertyType == typeof(int))
                {
                    valor = RandomNumber(18, 50);
                }
                else
                {
                    valor = new byte[80];
                    RandomBytes((byte[])valor);
                }

                propriedade.SetValue(objeto, valor);
            }

            return objeto;
        }

        public static IEnumerable<T> GenerateList<T>(int elementos = 10) where T : class, new()
        {
            IList<T> returned = new List<T>();
            for (int i = 0; i < elementos; i++)
                returned.Add(GenerateOne<T>());
            return returned;
        }
    }
}
